<?php
/**
 * Created by PhpStorm.
 * User: aDaddy
 * Date: 2016/7/25
 * Time: 9:55
 */

namespace App\Model\LazyCommon;
use App\Model\LazyCommon\MoneyModel;
use App\Model\LazyCommon\OrdersModel;
use App\Base\BaseConfig;
use App\Base\BaseModel;
use App\Model\LazyCommon\UserModel;
use App\Entity\UserInvite;
use App\Entity\UserInviteBonus;

//use App\Setting\LazyCommon\UserInviteSetting;

class UserInviteModel extends BaseModel{

    private $inviteBonusOpen = 1;
    private $inviteBonus4BuyOpen = 1;


    public function getRep()
    {
        return  $this->getDoctrine()->getRepository("App:UserInvite");
    }



    /****************************************** 私有 *****************************************/

    /**
     * @param $uid
     * @return UserInvite
     */
    public function getUser($uid)
    {
        $userInvite = $this->getRep()->findOneBy(array("uid"=> $uid));

        if (!$userInvite) {
            $userInvite = $this->addUser($uid);
        }
        return $userInvite;
    }

    /**
     * @param $code
     * @return UserInvite
     */
    public function getUserByCode($code)
    {
        return $this->getRep()->findOneBy(array("code"=> $code));
    }

    /**
     * @param $id
     * @return UserInvite
     */
    public function get($id)
    {
        return $this->getRep()->find($id);
    }


    //添加新记录
    //-------新加入用户时离自己最近的parent Id越靠前
    //-------如果通过explode函数分解，直接上级ID为0位
    /**
     * @param $uid
     * @param string $code
     * @return UserInvite
     */
    public function addUser( $uid , $code = "" )
    {//主要功能：添加记录到userInvite表，userInviteBonus添加一条待领取的记录，等用户收入达到100后领取
        if (!$code) {
            $parents = "";
        } else {
            $parentUser = $this->getUserByCode($code);
//            var_dump($parentUser);
            if (!$parentUser) {
                $parents = "";
            } else {
                if (!$parentUser->getParent()) {
                    $parents = $parentUser->getUid();
                } else {
                    $parentArray = $this->getUserParentsIdArray($parentUser->getUid());
                    array_unshift($parentArray, $parentUser->getUid());
                    $parents = implode(",",$parentArray);
                }

                $parents = ",$parents,";
            }
        }
        $UserInvite = $this->getRep()->findOneBy(array("uid"=> $uid));
        if (!$UserInvite) {
            $UserInvite = new UserInvite();
        }
        $UserInvite->setUid($uid)
            ->setParent($parents)
            ->setCode(base64_encode(md5($UserInvite->getUid().BaseConfig::__VI__)));
        $this->em->persist($UserInvite);
        $this->em->flush();

        //用户添加完成之后应该添加奖励
        //1：邀请奖励
        if ($this->inviteBonusOpen && $parents != "") {
            //添加奖励
            $UserInviteBonusModel = new UserInviteBonusModel($this->getDoctrine());
            $userParents = $this->getUserParentsIdArray($uid);
            if (isset($userParents[1])){
                $pid = $userParents[1];
                $UserInviteBonusModel->addUserInviteBonus($pid,$uid);
            }
        }

        return $UserInvite;
    }

    public function removeUser($parent_uid)
    {
        $rst = $this->getRelateUser($parent_uid);
//        var_dump($rst);
        foreach ($rst as $row) {
            $uid = $row["uid"];
            $userInvite = $this->getUser($uid);
            $parentStr = str_replace(",$parent_uid,",",",$userInvite->getParent());
            $userInvite->setParent($parentStr);
            $this->em->persist($userInvite);
        }
        $this->em->flush();
    }

    public function getRelateUser($uid)
    {
        $qb = $this->em->createQueryBuilder();
        $qb->from("App:UserInvite","UserInvite")
            ->select("UserInvite.uid")
            ->where(
                $qb->expr()->like("UserInvite.parent",":parent")
            );
        $qb->setParameter("parent","%,$uid,%");
        return $qb->getQuery()->getResult();
    }

    //获取邀请我的人所有上级

    /**
     * @param $uid
     * @return array
     */
    public function getUserParentsIdArray($uid)
    {
        $userInvite = $this->getUser($uid);
        if (!$userInvite) {
            return array();
        }
        $parentsStr = $userInvite->getParent();
        if (!$parentsStr) {
            return array();
        } else {
            return $this->myExplodeNumbers($parentsStr);
        }
    }

    public function getSons($uid,$page = 0 , $limit = 50)
    {
        $qb = $this->getQueryBuilder();
        $qb->select("A.*")->from("User_Invite","A");
        $qb->where(
            $qb->expr()->like("A.parent",":uid")
        );
        $qb->setParameter("uid",",$uid,%");//用户直接推荐的parent字段首位应该是父级用户的ID，所以通配符为UID%
        $qb->orderBy("A.id","DESC");
        $rst = $qb->execute()->fetchAll();

        return $rst;
    }


    public function getSonsTree($uid,$targetLevel = 0,$level = 0)
    {
        $me = $this->getUser($uid);
        $UserModel = new UserModel($this->getDoctrine());
        $MoneyModel = new MoneyModel($this->getDoctrine());
        $OrdersModel = new OrdersModel($this->getDoctrine());
        $userInfo = $UserModel->getUserById($me->getUid());
        $money = $MoneyModel->getUserMoney($me->getUid());
        $userData = $UserModel->getBaseInfo($userInfo);
        $userData["moneyObj"] = $money;
        $userData["orders"] = $orderNum = $OrdersModel->getUserOrdersNum($uid);
        $data["id"] = $me->getUid();
        $data["code"] = $me->getCode();
        $data["groups"] = $userInfo->getGroups();
        $data["level"] = $level;
        $data["info"] = $userData;
        $data["money"] = $money->getSumIn();



        if ($targetLevel !=0 && $level >= $targetLevel) {
            $data["sons"] = [];
            return $data;
        }
        $rst = $this->getSons($uid,0,999999999);
        if ($rst) {
            $sons = [];
            $level++;
            foreach ($rst as $row) {
                $son_id = $row["uid"];
                $sons[] = $this->getSonsTree($son_id,$targetLevel,$level);
            }
            $data["sons"] = $sons;
        } else {
            $data["sons"] = [];
        }
        return $data;
    }

    public function getSonsIds($data,&$return,$type = "")
    {

        if (isset($return[0])) {
            $return[0] = [];
        }
        foreach ($data["sons"] as $row) {
            $return[0][] = $row["id"];
            if ($type == "reg") {
                if ($row["groups"] != 3) {

                }else{
                    $return[$row["level"]][] = $row["id"];
                }
            }
            if ($type == "buy") {
                if ($row["groups"] <= 3 ) {

                }else{
                    $return[$row["level"]][] = $row["id"];
                }
            }
            $this->getSonsIds($row,$return,$type);
        }
        if (!$return) {
            return [];
        }
        ksort($return);
        return $return;
    }


//    public function getUserListFromSonIds()
//    {
//        $UserModel = new UserModel($this->getDoctrine());
//        $rep = $UserModel->em->createQueryBuilder();
//        $rep->from()
//    }


}